// Copyright 2009 StarCite Inc.  All rights reserved.
// HttpUtil.java 11:27:12 AM danny.liu
package com.billowsoft.tool.train.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * @author danny.liu Feb 2, 2012
 * @version 1.0
 * 
 */
public class HttpUtil {

	private static Log LOG = LogFactory.getLog(HttpUtil.class);

	public static String sendFormBasedRequest(DefaultHttpClient httpClient,
			String url, Map<String, String> params, Header... headers) throws Exception {
		HttpPost queryRequest = new HttpPost(url);

		List<NameValuePair> queryParams = new ArrayList<NameValuePair>();
		for (Entry<String, String> param : params.entrySet()) {
			queryParams.add(new BasicNameValuePair(param.getKey(), param
					.getValue()));
		}
		
		for(Header header : headers){
			queryRequest.addHeader(header);
		}
		queryRequest
				.setEntity(new UrlEncodedFormEntity(queryParams, HTTP.UTF_8));

		HttpResponse queryResponse = httpClient.execute(queryRequest);
		LOG.info("Response status: " + queryResponse.getStatusLine());
		HttpEntity entity = queryResponse.getEntity();
		try {
			String entityContent = EntityUtils.toString(entity,
					EntityUtils.getContentCharSet(entity));
			LOG.info(entityContent);
			return entityContent;
		} finally {
			EntityUtils.consume(entity);
		}
	}
	
	public static void getStreamResource(DefaultHttpClient httpClient, String url, String destFile){

		HttpGet getResourceRequest = new HttpGet(url);
		try {
			HttpResponse getResourceResponse = httpClient.execute(getResourceRequest);
			HttpEntity entity = getResourceResponse.getEntity();
			InputStream stream = entity.getContent();
			FileOutputStream outputStream = new FileOutputStream(new File(destFile));
			byte[] content = new byte[2048];
			int size = stream.read(content);
			while (size > 0) {
				outputStream.write(content, 0, size);
				size = stream.read(content);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
